<template>
  <div class="container">
<!--    <div v-if="filedata">-->
<!--      <van-button @click="saveFile">下载</van-button>-->
<!--    </div>-->

    <div class="mb20">{{websocketServerAddress}}</div>
    <div class="flex-row mb20" v-if="!linkedWebsocketServer">
      <div class="flex1">
        <van-button
        
        @click="startServer">startServer</van-button>
      </div>

      <div style="width: 90px;">OR</div>

      <div class="flex-row flex1">
        <van-field v-model="websocketServerAddress"></van-field> 
        <van-button @click="linkWebsocketServer">startSocket</van-button>
      </div>
    </div>

    <div class="row" >
      <div class="clients">
        <div class="client"
             :class="{'current': clientkey === currentClientId, 'mine': clientkey === myclientkey}"
             @click="selectClient(clientkey)"
             v-for="clientkey in clientKeys" :key="clientkey">
          {{clientkey}}
        </div>
      </div>

      <div>
      

        <div class="p" style="width: 600px;">
          <van-progress :percentage="getFilePercentage()" />
        </div>

        <div class="p">
          <van-field v-model="fileName" disabled></van-field>
        </div>

        <input id="fileCom"
               @input="onFileChange"
               type="file">
        <van-button
            :disabled="!currentClientId"
            @click="sendFile">发送</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { FileSlicer, saveByteArray } from "../utils/filesys";

import io from 'socket.io-client'
import { saveFile, SaveFile } from '../utils/file'
import { desktopDir } from "../utils/path"

const IP = global.ip.address()

let socket
let currentSaveFile = null
let fileSlicer

function startSocket(address) {
  console.log('address', address)
  context.websocketServerAddress = address
  context.linkedWebsocketServer = true
  socket = io(address, { 'reconnect': true })

  socket.on('file-send', function (httpData) {
     context.filePercentage = parseInt((httpData.index + 1) / httpData.bufferLength * 100)

    if (httpData.isFirst) {
      currentSaveFile = new SaveFile()
    }

    if (currentSaveFile) {
      if (httpData.isEnd) {
        currentSaveFile.append(httpData.slice)
        saveFile(currentSaveFile.getValue(), desktopDir, {
          filename: httpData.fileName,
          type: httpData.type
        })
        context.$notify({ type: 'success', message: '保存成功' });
      } else {
        currentSaveFile.append(httpData.slice)
      }
    }
  })

  socket.on('reconnecting', function (data) { 
    console.log("reconnecting"); 
  });

  socket.on('reconnect', function (data) { 
     console.log("reconnect"); 
       socket.emit('conneted', IP + '_' + global.os.userInfo().username);
  });

  socket.on('myclient', function (data) {
    context.socketStarted = true
    context.myclientkey = data
  })

  socket.on('update', function (data) {
    context.clients = jsonToMap(data)
    context.clientKeys = Array.from( context.clients.keys())
    context.currentClientId = ''
    console.log(context.clientKeys)
  })

  socket.on('disconnect', function() {
    console.log("disconnect")
    fileSlicer = false
  })

  socket.emit('conneted', IP + '_' + global.os.userInfo().username);

  // setInterval(() => {
  //   socket.emit('keep', 'live');
  // }, 1000 * 60)
}

import mime from 'mime'

import { Progress  as VanProgress } from 'vant'
import {jsonToMap} from "../utils/map";

global.electron.ipcRenderer.on('receive', function (e, data) {
  startSocket(data)
})

global.electron.ipcRenderer.on('servererror', function (e, data) {
  console.log('servererror', data + '')
})

let context = {}
export default {
  name: 'HelloWorld',
  components: {
    VanProgress
  },
  props: {
    msg: String,
  },
  data() {
    return {
      filedata: {},
      filePercentage: 0,
      clients: new Map(),
      clientKeys: [],
      currentClientId: '',
      fileName: '',
      myclientkey: '',
      linkedWebsocketServer: false,
      websocketServerAddress: ''
    }
  },
  mounted() {
    context = this
    this.websocketServerAddress = `http://${IP}:3200`
  },
  methods: {
    getFilePercentage() {
      return this.filePercentage
    },
    onFileChange() {
      var file = document.getElementById('fileCom').files.item(0)
      var fileNameArr = file.name.split('.')
      this.fileName = fileNameArr[0]
    },
    sendFile() {
      var self = this
      var file = document.getElementById('fileCom').files.item(0)
      fileSlicer = new FileSlicer(file);
      var fileNameArr = file.name.split('.')
      var fileExtension = fileNameArr[1]
      for(let i = 0; i < fileSlicer.slices; ++i) {
        setTimeout(function() {
          if (fileSlicer) {
            socket.emit('file', {
              index: i,
              fileName: fileNameArr[0],
              bufferLength: fileSlicer.slices,
              clientid: self.currentClientId,
              isFirst: (i === 0),
              isEnd: (i === fileSlicer.slices - 1),
              slice: fileSlicer.getNextSlice(),
              type: mime.getType(fileExtension)
            })
          }
        }, 300 * i)
      }
      this.filedata = null
    },
    selectClient(clientkey) {
      console.log('clientkey', clientkey)
      this.currentClientId = clientkey
    },
    startServer() {
      global.electron.ipcRenderer.send('newModal')
    },
    linkWebsocketServer() {
      startSocket(this.websocketServerAddress)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
  .row {
    display: flex;
    max-width: 900px;
    margin: 0 auto;
    margin-bottom: 50px;
    letter-spacing: 1px;
  }

  .p {
    margin-bottom: 20px;
  }

  .clients {
    width: 270px;
    padding-right: 30px;
  }
  .client {
    height: 50px;
    cursor: pointer;
    line-height: 50px;
    &.current {
      background-color: #1989fa;
      color: #ffffff;
    }
    &.mine {
      display: none;
    }
  }
</style>
